# -*- coding: utf-8 -*- 
"""
@Author : Chan ZiWen
@Date : 2022/7/1 13:23
File Description:

"""
import datetime
import sys
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime as D


def awayGoHome(date: str, log_time: list, timeRanges: list = None, filters_before: list = None, filters_after: list = None,
               Home_time: list = None, HomeRange: list = None, threshold: list = None):
    """log_time与res_s的值一一对应
    计算每天全量用户家中有离回家的设备：
        避免识别到笔记本，电脑等不是移动设备（在家办公）：设置 白天（4-11点） 晚上（15-24点）

    通过filter去匹配。
    log_time: [timestamp1, timestamp2, ...] , 表示当前时间是在局域网内, shape of (n,)
    :return:
    """
    if not timeRanges:
        timeRanges = [' 04:00', ' 11:00', ' 14:00', ' 23:59']

    if not threshold:
        a, b, c = 20, 30, 50
    else:
        a, b = threshold[0], threshold[1]
        c = a + b
    if not filters_before:
        filters_before = [1] * a + [0] * b
        filters_before = np.array(filters_before)

    if not filters_after:
        filters_after = [0] * b + [1] * a
        filters_after = np.array(filters_after)

    if not Home_time:
        awayHome_start = int(time.mktime(time.strptime(date + timeRanges[0], "%Y-%m-%d %H:%M")))    # 10 bit
        awayHome_end = int(time.mktime(time.strptime(date + timeRanges[1], "%Y-%m-%d %H:%M")))
        goHome_start = int(time.mktime(time.strptime(date + timeRanges[2], "%Y-%m-%d %H:%M")))
        goHome_end = int(time.mktime(time.strptime(date + timeRanges[3], "%Y-%m-%d %H:%M")))
    else:
        awayHome_start = Home_time[0]
        awayHome_end = Home_time[1]
        goHome_start = Home_time[2]
        goHome_end = Home_time[3]

    if not HomeRange:
        awayHomeRange = [i + awayHome_start for i in range(0, (awayHome_end - awayHome_start), 60)]
        goHomeRange = [i + goHome_start for i in range(0, (goHome_end - goHome_start), 60)]
    else:
        awayHomeRange = HomeRange[0]
        goHomeRange = HomeRange[1]

    # list to Dataframe
    df_awayHome = pd.DataFrame(
        {'isOnline': [0] * ((awayHome_end - awayHome_start)//60)},
        index=awayHomeRange
    )
    df_goHome = pd.DataFrame(
        {'isOnline': [0] * ((goHome_end - goHome_start)//60)},
        index=goHomeRange
    )

    # generate completed Dataframe
    away_nums, go_nums = 0, 0

    for time_i in log_time:
        time_i = int(time_i)//1000
        second = datetime.datetime.fromtimestamp(time_i).second
        if second >= 30:
            time_i_ = time_i + (60 - second)
        else:
            time_i_ = time_i - second
        if awayHome_start <= time_i <= awayHome_end:
            df_awayHome.loc[time_i_, 'isOnline'] = 1
            away_nums += 1
        elif goHome_start <= time_i <= goHome_end:
            df_goHome.loc[time_i_, 'isOnline'] = 1
            go_nums += 1
        else:
            continue
    res_flag = 0
    # 遍历 出门数据

    awayHome_values = df_awayHome['isOnline'].values
    goHome_values = df_goHome['isOnline'].values

    if len(awayHome_values) >= a:
        for i in range(c, len(awayHome_values)-c):
            temp = awayHome_values[(i - c):i]
            res = abs(np.logical_and(temp, filters_before).sum() - a)
            if res <= 2:
                # print(res, end='  ')
                res_flag += 1
                break

    # 遍历 回家数据
    if len(goHome_values) >= a:
        # pd.Series(goHome_values, index=range(len(goHome_values))).plot()
        # plt.show()
        for i in range(c, len(goHome_values)-c):
            temp = goHome_values[(i - c):i]
            res = abs(np.logical_and(temp, filters_after).sum() - a)
            if res <= 2:
                # print(res, end='  ')
                res_flag += 1
                break

    return True if res_flag == 2 else False


def awayGoHome_14():
    """
    计算每天全量用户 家中 14天中有10天存在有离回家记录的设备
    :return:
    """

    return